﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    using System.Data;
    using System.Data.SqlClient;
    class DBHelper
    {
        static string StrConn { get; set; }
        static DBHelper()
        {
            StrConn = System.Configuration.ConfigurationManager.ConnectionStrings["StrConn"].ConnectionString;
        }
        public static int ExecuteNonQuery(string sql, params SqlParameter[] sps)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                if (sps != null && sps.Length > 0)
                    cmd.Parameters.AddRange(sps);
                return cmd.ExecuteNonQuery();
            }
        }
        //普通SQL语句的查询
        public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] sps)
        {
            SqlConnection conn = new SqlConnection(StrConn);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            if (sps != null && sps.Length > 0)
                cmd.Parameters.AddRange(sps);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        public static object ExecuteScalar(string sql, params SqlParameter[] sps)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                if (sps != null && sps.Length > 0)
                    cmd.Parameters.AddRange(sps);
                return cmd.ExecuteScalar();
            }           
        }
        /// <summary>
        /// 调用存储过程的
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="sps"></param>
        /// <returns></returns>
        public static SqlDataReader Proc_ExecuteReader(string sql, params SqlParameter[] sps)
        {
            SqlConnection conn = new SqlConnection(StrConn);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.CommandType = CommandType.StoredProcedure;
            if (sps != null && sps.Length > 0)
                cmd.Parameters.AddRange(sps);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

        public static object Proc_ExecuteScalar(string sql, params SqlParameter[] sps)
        {
            using (SqlConnection conn = new SqlConnection(StrConn))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                if (sps != null && sps.Length > 0)
                    cmd.Parameters.AddRange(sps);
                return cmd.ExecuteScalar();
            }
        }
    }
}
